﻿Public Class ProxyFactory
    Private Const Pattern_ServicePath As String = "{0}DesktopModules/IWebCF/CoreService.svc{1}"

    Private _isSSL As Boolean = False
    Private _serviceUrl As Uri


    Public Sub New(ByVal portalUrl As String)
        Dim tempUri As New Uri(portalUrl)

        Me.ServiceUrl = tempUri

        Me.IsSSL = tempUri.Scheme.StartsWith("https")

    End Sub

    Public Sub New(ByVal portalUri As Uri)

        Me.ServiceURL = portalUri
        Me.IsSSL = portalUri.Scheme.StartsWith("https")

    End Sub

    Public Sub New(ByVal isSsl As Boolean, ByVal hostname As String)

        Me.IsSSL = isSsl

        Me.ServiceUrl = New Uri(IIf(isSsl, "https://", "http://") & hostname)

    End Sub

    Public Property ServiceUrl() As Uri
        Get
            Return Me._serviceUrl
        End Get
        Set(ByVal value As Uri)

            Me._serviceUrl = value

        End Set
    End Property

    Public Property IsSSL() As Boolean
        Get
            Return _isSSL
        End Get
        Set(ByVal value As Boolean)
            _isSSL = value
        End Set
    End Property


    <Obsolete("Uses reflection and has a performance cost.")> _
    Public Function GetProxy(Of T)() As T

        Dim endpointName As String = String.Empty

        If GetType(T).GetInterface(GetType(Service.IWebCoreService).Name) IsNot Nothing Then

            endpointName = CoreEndPoints.CoreService

        ElseIf GetType(T).GetInterface(GetType(Service.IWebFileManager).Name) IsNot Nothing Then

            endpointName = CoreEndPoints.WebFileManager

        ElseIf GetType(T).GetInterface(GetType(Service.IWebFileTransferManager).Name) IsNot Nothing Then

            endpointName = CoreEndPoints.WebFileTransferManager

        ElseIf GetType(T).GetInterface(GetType(Service.IWebFileTransferManager).Name) IsNot Nothing Then
            endpointName = CoreEndPoints.WebUserManager

        End If


        Return GetProxy(Of T)(endpointName)

    End Function

    Public Function GetProxy(Of T)(ByVal endpointName As String) As T

        Return GetProxy(Of T)(endpointName, GetEndPointURL(endpointName))

    End Function

    Public Function GetProxy(Of T)(ByVal endpointName As String, ByVal websiteUrl As String) As T

        Return DirectCast(Activator.CreateInstance(GetType(T), endpointName, websiteUrl), T)

    End Function

    Private Function GetEndPointURL(ByVal endpointName As String) As String

        If endpointName = CoreEndPoints.CoreService Then
            Return String.Format(Pattern_ServicePath, ServiceUrl, String.Empty)
        End If

        Return String.Format(Pattern_ServicePath, ServiceUrl, String.Format("/{0}", endpointName))

    End Function

End Class